﻿using gt.IdentityServer.Data;
using gt.IdentityServer.Services;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace gt.IdentityServer.Extensions
{
    public class AppUserProfileService : IProfileService
    {
        private readonly ILoginService _loginService;
        private readonly ILogger<AppUserProfileService> _logger;
        public AppUserProfileService(ILoginService loginService,
            ILogger<AppUserProfileService> logger)
        {
            _loginService = loginService;
            _logger = logger;
        }

        public async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var userId = context.Subject?.GetSubjectId();
            _logger.LogInformation($"find present sujectid:{userId}");
            if (userId == null) throw new Exception("no sujectId present");

            //todo 重复请求，是否可以从当前的context验证是否已有对应的claim，则不必要再次去search
            //var tempClaims = context.Subject.Claims.ToList();

            var user = await _loginService.FindUserInfoByIdAsync(int.Parse(userId));
            var clamis = _loginService.GetClaims(user);

            _logger.LogDebug($"requestd claims types:{string.Join(',', context.RequestedClaimTypes)}");

            //context.IssuedClaims.AddRange(clamis);
            context.AddRequestedClaims(clamis);
            /*
            //判断是否有请求Claim信息
            if (context.RequestedClaimTypes.Any())
            {
                //根据用户唯一标识查找用户信息
                var userId = int.Parse(context.Subject.GetSubjectId());
                var user = _userContext.Users.Find(userId);
                if (user != null)
                {
                    //调用此方法以后内部会进行过滤，只将用户请求的Claim加入到 context.IssuedClaims 集合中 这样我们的请求方便能正常获取到所需Claim
                    var claims = new List<Claim>
                    {
                        new Claim("name",user.Name),
                        new Claim("sex",user.Sex.ToString()),
                        new Claim("introduce",user.Introduce),
                    };
                    context.AddRequestedClaims(claims);
                }
            }*/
        }

        public async Task IsActiveAsync(IsActiveContext context)
        {
            context.IsActive = true;
            await Task.CompletedTask;
        }
    }
}
